package com.kfyang.manualgear.daoplugin.reference;

import com.intellij.openapi.util.TextRange;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.*;
import com.intellij.util.ProcessingContext;
import com.kfyang.manualgear.daoplugin.Constants;
import com.kfyang.manualgear.daoplugin.util.PsiUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FragReferenceContributor extends PsiReferenceContributor {
    // 匹配 [xxx]
    private static final Pattern FRAG_PATTERN = Pattern.compile("\\[(.*?)]");

    @Override
    public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
        registrar.registerReferenceProvider(PlatformPatterns.psiElement(PsiLiteralExpression.class),
            new PsiReferenceProvider() {
                @NotNull
                @Override
                public PsiReference @NotNull [] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {

//                    System.out.println(element.getClass() + " " + element.getText());

                    ArrayList<PsiReference> referenceList = new ArrayList<>();
                    PsiElement annotation0 = PsiUtils.findParent(element, 3);
                    if (!(annotation0 instanceof PsiAnnotation annotation) ||
                        (
                            !Constants.MODIFY_ANNO.equals(annotation.getQualifiedName()) &&
                                !Constants.SELECT_ANNO.equals(annotation.getQualifiedName())
                        )
                    ) {
                        return new PsiReference[0];
                    }
                    PsiElement method0 = PsiUtils.findParent(element, 5);
                    if (!(method0 instanceof PsiMethod)) {
                        return new PsiReference[0];
                    }

                    Matcher matcher = FRAG_PATTERN.matcher(element.getText());

                    while (matcher.find()) {
                        String fragName = matcher.group(1);
                        referenceList.add(new FragReference(element, new TextRange(matcher.start(1), matcher.end(1)), fragName));
                    }
//                    System.out.println(referenceList.size());
                    return referenceList.toArray(new PsiReference[0]);
                }
            });
    }

}
